package utils

import (
	"fmt"
	"os"
	"sync"

	"github.com/joho/godotenv"
)

type Env struct {
	SERVER_ENDPOINT string

	REDIS_HOST     string
	REDIS_PORT     string
	REDIS_PASSWORD string
	REDIS_DB       string

	SMTP_HOST     string
	SMTP_PORT     string
	SMTP_USERNAME string
	SMTP_PASSWORD string
	SMTP_FROM     string

	ALIPAY_APP_ID      string
	ALIPAY_PRIVATE_KEY string
	ALIPAY_PUBLIC_KEY  string
	ALIPAY_GATEWAY     string

	POSTGRES_HOST     string
	POSTGRES_PORT     string
	POSTGRES_USER     string
	POSTGRES_PASSWORD string
	POSTGRES_DB       string
	POSTGRES_SSLMODE  string
}

var (
	ENV     *Env
	envOnce sync.Once
)

func init() {
	envOnce.Do(func() {
		loadEnv()
	})
}

func preLoggerPrint(format string, v ...interface{}) {
	fmt.Printf(format+"\n", v...)
}

func loadEnv() {
	// 判断路径下是否有.env.dev和.env，如果有，优先采用.env.dev
	envFile := ".env"
	if _, err := os.Stat(".env.dev"); err == nil {
		envFile = ".env.dev"
	}
	if err := godotenv.Load(envFile); err != nil {
		preLoggerPrint("无法加载文件%s: %v", envFile, err)
		os.Exit(1)
	}
	preLoggerPrint("环境变量加载完成: %s", envFile)

	ENV = &Env{}
	ENV.SERVER_ENDPOINT = GetEnv("SERVER_ENDPOINT", "http://localhost:8080")

	ENV.REDIS_HOST = GetEnv("REDIS_HOST", "localhost")
	ENV.REDIS_PORT = GetEnv("REDIS_PORT", "6379")
	ENV.REDIS_PASSWORD = GetEnv("REDIS_PASSWORD", "")
	ENV.REDIS_DB = GetEnv("REDIS_DB", "0")

	ENV.SMTP_HOST = GetEnv("SMTP_HOST", "smtp.qq.com")
	ENV.SMTP_PORT = GetEnv("SMTP_PORT", "587")
	ENV.SMTP_USERNAME = GetEnv("SMTP_USERNAME", "jabberwocky240@qq.com")
	ENV.SMTP_PASSWORD = GetEnv("SMTP_PASSWORD", "cfaqcklrhcbzeadc")
	ENV.SMTP_FROM = GetEnv("SMTP_FROM", "jabberwocky240@qq.com")

	ENV.ALIPAY_APP_ID = GetEnv("ALIPAY_APP_ID", "9021000149654839")
	ENV.ALIPAY_PRIVATE_KEY = GetEnv("ALIPAY_PRIVATE_KEY", "")
	ENV.ALIPAY_PUBLIC_KEY = GetEnv("ALIPAY_PUBLIC_KEY", "")
	ENV.ALIPAY_GATEWAY = GetEnv("ALIPAY_GATEWAY", "https://openapi.alipay.com/gateway.do")

	ENV.POSTGRES_HOST = GetEnv("POSTGRES_HOST", "localhost")
	ENV.POSTGRES_PORT = GetEnv("POSTGRES_PORT", "5432")
	ENV.POSTGRES_USER = GetEnv("POSTGRES_USER", "enzyme")
	ENV.POSTGRES_PASSWORD = GetEnv("POSTGRES_PASSWORD", "enzyme")
	ENV.POSTGRES_DB = GetEnv("POSTGRES_DB", "enzyme")
	ENV.POSTGRES_SSLMODE = GetEnv("POSTGRES_SSLMODE", "disable")
}

func GetEnv(key string, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	preLoggerPrint("环境变量%s未设置，使用默认值: %s", key, defaultValue)
	return defaultValue
}
